package org.example;

/**
 * @Auther: wangbw
 * @Date:2020/9/25
 * @Description: org.example
 * @version: 1.0
 */
public class BitCount {
    public static void main(String[] args) {
        int i = Integer.MAX_VALUE;
        System.out.println(intToBinary32(i, 32));
        int count = bitCount(i);
        System.out.println(count);
    }

    public static int bitCount(int i) {
        // HD, Figure 5-2
        i = i - ((i >>> 1) & 0x55555555);
        i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
        i = (i + (i >>> 4)) & 0x0f0f0f0f;
        i = i + (i >>> 8);
        i = i + (i >>> 16);
        return i & 0x3f;
    }

    public static int bitCount2(int j){
        int count = 0;
        while (j > 0){
            System.out.print(Integer.toBinaryString(j) + "\t" + Integer.toBinaryString(j - 1) + "\t");
            j = j & (j - 1);
            System.out.println(Integer.toBinaryString(j) + "\t");
            count++;
        }
        return count;
    }



    public static String intToBinary32(int i, int bitNum){
        String binaryStr = Integer.toBinaryString(i);
        while(binaryStr.length() < bitNum){
            binaryStr = "0"+binaryStr;
        }
        return binaryStr;
    }

}
